package com.bilibili.dubbo.api;

import com.bilibili.dubbo.api.mongo.FriendApi;
import com.bilibili.model.mongo.Friend;
import com.bilibili.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


/**
 * @author HuangRongFu
 * 2021/11/24 星期三11:20 上午
 */

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加联系人
     *
     * @param: loginUserId
     * @param: userId
     */
    @Override
    public void addContact(Long loginUserId, Long userId) {

        Query query1 = new Query(Criteria.where("userId").is(loginUserId).and("friendId").is(userId));

        long currentTimeMillis = System.currentTimeMillis();

        //不存在 则保存
        if (!mongoTemplate.exists(query1, Friend.class)){

            Friend friend = new Friend();

            friend.setUserId(loginUserId);
            friend.setFriendId(userId);
            friend.setCreated(currentTimeMillis);

            mongoTemplate.save(friend);
        }

        Query query2 = new Query(Criteria.where("userId").is(userId).and("friendId").is(loginUserId));

        if (!mongoTemplate.exists(query2, Friend.class)){

            Friend friend = new Friend();

            friend.setUserId(userId);
            friend.setFriendId(loginUserId);
            friend.setCreated(currentTimeMillis);

            mongoTemplate.save(friend);
        }
    }

    /**
     * 联系人列表
     * @param:  page
     * @param:  pageSize
     * @param:  heyWord
     * @Return: PageResult
     */
    @Override
    public PageResult findContact(Long page, Long pageSize, Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId));

        long total = mongoTemplate.count(query, Friend.class);

        Long start = (page -1) * pageSize;

        List<Friend> friendList = new ArrayList<>();

        if (total > start) {

            query.skip(start).limit(pageSize.intValue());

            friendList = mongoTemplate.find(query, Friend.class);

        }

        return  new PageResult(page, pageSize, total,friendList);
    }
}
